package com.thghh.maven;

import cn.hutool.core.io.FileUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 分析依赖
 *
 * @author pengzhikang
 * @date 2022/12/16 17:09
 * @since 1.0.0
 */
public class GenerateDependenciesApp {

    public static void main(String[] args) throws JsonProcessingException {
        GenerateDependenciesApp app = new GenerateDependenciesApp();
        app.generateDependenciesApp();
    }

    private void generateDependenciesApp() throws JsonProcessingException {
        List<String> textList = FileUtil.readLines(Objects.requireNonNull(getClass().getResource("maven.txt")), StandardCharsets.UTF_8);

        List<String> dependenciesTextsList = textList.stream().map(p -> p.replace("[WARNING]", "").trim()).collect(Collectors.toList());

        List<Dependency> dependencyList = new ArrayList<>();
        List<Exclusion> undependencyList = new ArrayList<>();

        String flag = null;
        for (String text : dependenciesTextsList) {
            if ("Used undeclared dependencies found:".equals(text)) {
                flag = "declared";
                continue;
            } else if ("Unused declared dependencies found:".equals(text)) {
                flag = "undeclared";
                continue;
            }
            String[] texts = text.split(":");

            if ("declared".equals(flag)) {
                Dependency dependency = new Dependency(texts[0], texts[1], texts[2], texts[3], texts[4]);
                dependencyList.add(dependency);
            } else if ("undeclared".equals(flag)) {
                Exclusion dependency = new Exclusion(texts[0], texts[1], texts[2], texts[3], texts[4]);
                undependencyList.add(dependency);
            }
        }

        // 根据group id排序
        dependencyList.sort(Comparator.comparing(Dependency::getGroupId));
        // undependencyList.sort(Comparator.comparing(Exclusion::getGroupId));

        ObjectMapper xmlMapper = new XmlMapper();
        ObjectWriter objectWriter = xmlMapper.writerWithDefaultPrettyPrinter();

        System.out.println("================找到已使用的未声明依赖项:================");
        for (Dependency dependency : dependencyList) {
            System.out.println(objectWriter.writeValueAsString(dependency));
        }
        System.out.println("\n================找到未使用的声明依赖项:================");
        for (Exclusion p : undependencyList) {
            System.out.print(objectWriter.writeValueAsString(p));
        }
    }


}
